import sensor, image
import display
import pyb
import os
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(30)
sensor.set_auto_gain(False)
sensor.set_auto_exposure(False)
sensor.set_auto_whitebal(False)
lcd = display.SPIDisplay()
p5 = pyb.Pin('P5', pyb.Pin.IN)
try:
	os.listdir('/sd')
	print("SD card already mounted.")
except OSError:
	os.mount(pyb.SDCard(), '/sd')
	print("SD card mounted successfully.")
last_save_time = pyb.millis()
save_interval = 2000
file_counter = 0
while True:
	img = sensor.snapshot()
	img.lens_corr(1.8)
	if p5.value() == 0:
		codes = img.find_qrcodes()
		if codes:
			for code in codes:
				corners = code.corners()
				for i in range(4):
					x0, y0 = corners[i]
					x1, y1 = corners[(i + 1) % 4]
					img.draw_line(x0, y0, x1, y1, color=(255, 0, 0))
				qr_text = code.payload()
				screen_width = sensor.width()
				screen_height = sensor.height()
				text_width = len(qr_text) * 8
				text_height = 16
				x_center = (screen_width - text_width) // 2
				y_center = (screen_height - text_height) // 2
				for dx in range(-1, 2):
					for dy in range(-1, 2):
						img.draw_string(10 + dx, 50 + dy, qr_text, color=(255, 0, 0), scale=2)
				print("QR Code:", code.payload())
				current_time = pyb.millis()
				if current_time - last_save_time >= save_interval:
									filename = "/sd/QR_{}.bmp".format(file_counter)
									img.save(filename)
									print("Saved image to", filename)
									last_save_time = current_time
									file_counter += 1
	else:
		img.clear()
		img.draw_string(10, 10, "NO QR Code", color=(255, 0, 0))
	lcd.write(img)